<?php
/**
 * Created by PhpStorm.
 * User: xiao
 * Date: 2018/9/10
 * Time: 16:14
 */

namespace app\user\service;


use app\common\base\BaseService;
use app\common\model\User;
use app\common\utils\JUtil;
use app\common\utils\NetUtil;

class UserOperationService extends BaseService
{


    public static function addWeChatUser()
    {
        $code = input('get.code', '');
        if (empty($code)) return JUtil::E('code error');

        $appId = 'wxbc432e36a688f3e6';
        $secret = '6f89dc98cbff9a8cd47c18eb0aac7949';

        $getOpenIdUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$secret}&js_code={$code}&grant_type=authorization_code";

        $data = NetUtil::GET($getOpenIdUrl, null, null, null, true);
        if (empty($data)) return JUtil::E('登录失败');

        $data = json_decode($data, true);
        if (empty($data)) return JUtil::E('登录失败');

        $openId = $data['openid'];
        $userModel = new User();
        try {
            $result = $userModel->findUserByWeChatOpenId($openId);
            if (empty($result)) {
                $nickname = input('get.nickname', 'test');
                $avatar = input('get.avatar', 'test');

                $result = $userModel->data(array(
                    'nickname' => $nickname,
                    'avatar' => $avatar,
                    'wechat_open_id' => $openId,
                ))->save();

                if ($result === false) {
                    return JUtil::E('添加失败');
                }
                $result = $userModel->findUserByWeChatOpenId($openId);

                return JUtil::SUCCESS($result);
            } else {
                // 返回用户信息
                return JUtil::SUCCESS($result);
            }
        } catch (\Exception $e) {
            return JUtil::SYSTEM_ERROR();
        }
    }


}